<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
      <p>我的订单记录</p>
    </div>

    <div class="orders-container" v-if="tableData && tableData.length > 0">
      <el-card v-for="item in tableData"  class="order-card">
        <div class="order-header">
          <div class="product-info">
            <div class="product-name">
              {{ item.productName }}
            </div>
            <div class="order-id">订单号: {{ item.id }}</div>
          </div>
          <el-tag :type="getStatusType(item.orderStatus)" class="status-tag">
            {{ getStatusText(item.orderStatus) }}
          </el-tag>
        </div>
        
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单金额:</span>
            <span class="value price">¥{{ item.totalAmount || '0.00' }}</span>
          </div>
          <div class="info-item">
            <span class="label">下单时间:</span>
            <span class="value">{{ formatDate(item.createTime) }}</span>
          </div>
          <div class="info-item" v-if="item.shengName || item.shiName">
            <span class="label">收货地址:</span>
            <span class="value">{{ item.shengName }} {{ item.shiName }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <div class="empty-orders" v-else>
      <el-empty description="暂无订单记录">
        <el-button type="primary" @click="goShopping">去购物</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { findList } from "@/assets/list.js";
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const tableData = ref([]);
const userId = localStorage.getItem('userId');

function getProductName(order) {
  // 打印订单数据以便调试
  console.log('订单数据:', order);
  
  if (!order) return '加载中...';
  
  // 尝试获取商品名称
  if (order.orderProducts && order.orderProducts.length > 0) {
    return order.orderProducts.map(p => p.productName ).join(', ');
  }
  
  if (order.products && order.products.length > 0) {
    return order.products.map(p => p.productName ).join(', ');
  }
  
  if (order.items && order.items.length > 0) {
    return order.items.map(p => p.productName).join(', ');
  }
  
  // 如果找不到商品名称，返回默认值
  return '未知商品';
}

function formatDate(timestamp) {
  if (!timestamp) return '未知时间';
  try {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    });
  } catch (e) {
    return '时间格式错误';
  }
}

function getList() {
  if (!userId) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  findList(userId).then(res => {
    console.log('API响应数据:', res);
    if (res.data && Array.isArray(res.data)) {
      tableData.value = res.data;
      // 打印每个订单的数据结构
      res.data.forEach((order, index) => {
        console.log(`订单 ${index + 1} 的完整数据:`, order);
      });
    } else {
      tableData.value = [];
      ElMessage.warning('暂无订单数据');
    }
  }).catch(err => {
    console.error('获取订单列表失败:', err);
    ElMessage.error('获取订单列表失败，请稍后重试');
    tableData.value = [];
  });
}

function goShopping() {
  router.push('/');
}

function getStatusType(status) {
  switch(status) {
    case 1: return 'warning'  // 待支付
    case 2: return 'success'  // 已支付
    case 3: return 'info'     // 已完成
    case 4: return 'danger'   // 已取消
    default: return 'info'
  }
}

function getStatusText(status) {
  switch(status) {
    case 1: return '待支付'
    case 2: return '已支付'
    case 3: return '已完成'
    case 4: return '已取消'
    default: return '未知状态'
  }
}

// 页面加载时获取订单列表
getList();
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.profile-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.profile-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.profile-header p {
  margin: 10px 0 0;
  color: #909399;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-card {
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.order-id {
  font-size: 12px;
  color: #909399;
}

.status-tag {
  font-size: 12px;
  margin-left: 15px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  color: #909399;
  font-size: 14px;
}

.value {
  color: #606266;
  font-size: 14px;
}

.value.price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.empty-orders {
  margin-top: 100px;
  text-align: center;
}
</style>
